import React, {useEffect} from 'react';
import {StatusBar} from 'expo-status-bar';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import useColorScheme from './hooks/useColorScheme';
import SplashImage from "./components/SplashImage";
import {AuthNavigation, Navigation} from "./navigation";
import AsyncStorage from '@react-native-community/async-storage';

export default function App() {

  const [isUpdateFinish, setUpdateFinish] = React.useState(false);
  const isLoadingComplete = useCachedResources();//资源检查
  const colorScheme = useColorScheme();//主题检查

  const [state, dispatch] = React.useReducer(
    (prevState: any, action: { type: any; token: any; }) => {
      switch (action.type) {
        case 'EXAMINE_TOKEN':
          return {
            ...prevState,
            haveToken: action.token
          };
      }
    },{
      haveToken: false,
    }
  );

  useEffect(() => {
    // 从存储中获取令牌，然后导航到我们合适的位置
    const bootstrapAsync = async () => {
      dispatch({type: 'EXAMINE_TOKEN', token: await _examineToken()});
    };
    bootstrapAsync().then(() => {
    });
  }, []);

  const authContext = React.useMemo(
    () => ({
      examineToken: async () => {
        dispatch({type: 'EXAMINE_TOKEN', token: await _examineToken()})
      }
    }),
    []
  );

  if (!isLoadingComplete || !isUpdateFinish) {//检查资源是否加载完毕
    return (<SplashImage onUpdate={(status: boolean) => {
      setUpdateFinish(status)
    }}/>)
  }
  return (
    <AuthContext.Provider value={authContext}>
      <SafeAreaProvider>
        {
          state.haveToken ? <Navigation colorScheme={colorScheme}/> : <AuthNavigation colorScheme={colorScheme}/>
        }
        <StatusBar/>
      </SafeAreaProvider>
    </AuthContext.Provider>
  );
}

const _examineToken = async () => {
  const userToken = await AsyncStorage.getItem('userToken');
  console.log("------用户token-----",userToken)
  return userToken;
}

const AUTH_CONTEXT_ERROR = '找不到身份验证上下文。 是否用AuthContext.Consumer包装了组件？';
export const AuthContext = React.createContext<{
  examineToken: () => void;
}>({
  examineToken: () => {
    throw new Error(AUTH_CONTEXT_ERROR);
  }
});

